package com.zy.ss;
import java.io.*;
import java.util.ArrayList;
import	java.util.List;

import com.google.gson.Gson;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.net.URLEncoder;
import java.util.Base64;
import java.util.Map;

/**
 * @author zhaoyi
 * @date 2021/3/5 18:22
 */
public class BodySeg {

    /**
     * 重要提示代码中所需工具类
     * FileUtil,Base64Util,HttpUtil,GsonUtils请从
     * https://ai.baidu.com/file/658A35ABAB2D404FBF903F64D47C1F72
     * https://ai.baidu.com/file/C8D81F3301E24D2892968F09AE1AD6E2
     * https://ai.baidu.com/file/544D677F5D4E4F17B4122FBD60DB82B3
     * https://ai.baidu.com/file/470B3ACCA3FE43788B5A963BF0B625F3
     * 下载
     */
    public static String body_seg(String filePath) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/body_seg";
        try {
            // 本地文件路径
            //String filePath = "D:\\data\\img\\55.jpeg";
            byte[] imgData = FileUtil.readFileByBytes(filePath);
            String imgStr = Base64Util.encode(imgData);
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");

            String param = "image=" + imgParam+"&type=foreground";


            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = "24.62d229d4c49a2d2c91618ec4ab2d5a18.2592000.1619950194.282335-23749809";

            String result = HttpUtil.post(url, accessToken, param);
            //System.out.println(result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {

        List<String> fs = new ArrayList<>();
        fs.add("C:\\Users\\Administrator\\Documents\\WeChat Files\\zy854032098\\FileStorage\\File\\2021-03\\专家\\专家\\鲍世韵.png");
        fs.add("C:\\Users\\Administrator\\Documents\\WeChat Files\\zy854032098\\FileStorage\\File\\2021-03\\专家\\专家\\陈汝福.png");
        fs.add("C:\\Users\\Administrator\\Documents\\WeChat Files\\zy854032098\\FileStorage\\File\\2021-03\\专家\\专家\\陈祖兵.png");
        fs.add("C:\\Users\\Administrator\\Documents\\WeChat Files\\zy854032098\\FileStorage\\File\\2021-03\\专家\\专家\\巩 鹏.png");
        fs.add("C:\\Users\\Administrator\\Documents\\WeChat Files\\zy854032098\\FileStorage\\File\\2021-03\\专家\\专家\\古松钢.png");
        fs.add("C:\\Users\\Administrator\\Documents\\WeChat Files\\zy854032098\\FileStorage\\File\\2021-03\\专家\\专家\\李 嘉.png");
        fs.add("C:\\Users\\Administrator\\Documents\\WeChat Files\\zy854032098\\FileStorage\\File\\2021-03\\专家\\专家\\廖锦岐.png");
        fs.add("C:\\Users\\Administrator\\Documents\\WeChat Files\\zy854032098\\FileStorage\\File\\2021-03\\专家\\专家\\刘吉奎.png");
        fs.add("C:\\Users\\Administrator\\Documents\\WeChat Files\\zy854032098\\FileStorage\\File\\2021-03\\专家\\专家\\王小忠.png");
        fs.add("C:\\Users\\Administrator\\Documents\\WeChat Files\\zy854032098\\FileStorage\\File\\2021-03\\专家\\专家\\谢德金.png");
        fs.add("C:\\Users\\Administrator\\Documents\\WeChat Files\\zy854032098\\FileStorage\\File\\2021-03\\专家\\专家\\严江.png");
        fs.add("C:\\Users\\Administrator\\Documents\\WeChat Files\\zy854032098\\FileStorage\\File\\2021-03\\专家\\专家\\詹勇强.png");
        fs.add("C:\\Users\\Administrator\\Documents\\WeChat Files\\zy854032098\\FileStorage\\File\\2021-03\\专家\\专家\\张耀明.png");


        for (String file : fs) {

            String s = BodySeg.body_seg(file);
            Map map = GsonUtils.fromJson(s, Map.class);
            String foreground = (String) map.get("foreground");
            String[] ss = file.split("专家");
            String s1 = ss[2];

            GenerateImage(foreground, "D:\\data\\img\\"+s1+".png");
        }








       /* String labelmap = (String) map.get("labelmap");
        List<Map> persons = (List<Map>) map.get("person_info");
        Double height = Double.parseDouble(persons.get(0).get("height").toString());
        Double width = Double.parseDouble(persons.get(0).get("width").toString());

        convert(labelmap,  width.intValue(),height.intValue());*/

    }


    public static String GetImageStr(String imgFilePath) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        byte[] data = null;

        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgFilePath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);// 返回Base64编码过的字节数组字符串
    }

    public static boolean GenerateImage(String imgStr, String imgFilePath) {// 对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) // 图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            // 生成jpeg图片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(bytes);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    public static BufferedImage resize(BufferedImage img, int newW, int newH) {
        Image tmp = img.getScaledInstance(newW, newH, Image.SCALE_SMOOTH);
        BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);

        Graphics2D g2d = dimg.createGraphics();
        g2d.drawImage(tmp, 0, 0, null);
        g2d.dispose();

        return dimg;
    }

    public static void convert(String labelmapBase64, int realWidth, int realHeight) {
        try {

            byte[] bytes = Base64.getDecoder().decode(labelmapBase64);
            InputStream is = new ByteArrayInputStream(bytes);
            BufferedImage image = ImageIO.read(is);
            BufferedImage newImage = resize(image, realWidth, realHeight);
            BufferedImage grayImage = new BufferedImage(realWidth, realHeight, BufferedImage.TYPE_BYTE_GRAY);
            for(int i= 0 ; i < realWidth ; i++){
                for(int j = 0 ; j < realHeight; j++){
                    int rgb = newImage.getRGB(i, j);
                    grayImage.setRGB(i, j, rgb * 255);  //将像素存入缓冲区
                }
            }
            File newFile = new File("D:\\data\\img\\gray.jpg");
            ImageIO.write(grayImage, "jpg", newFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
